package com.climber.android.auth.ui

import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.climber.android.auth.R
import com.climber.android.commonres.app.service.CoreService
import com.climber.android.commonres.app.service.OTPRequestType
import com.climber.android.commonres.helper.RxCountDown
import com.climber.android.commonres.helper.onClick
import com.climber.android.commonres.helper.showCountryCodeSpinner
import com.climber.android.commonres.ui.BaseMVPActivity
import com.climber.android.commonres.util.UIHelper
import com.climber.android.commonsdk.api.APIError
import com.climber.android.commonsdk.api.ApiObserver
import com.climber.android.commonsdk.api.GlobalErrorProcessor
import com.climber.android.commonsdk.api.entity.APIResponse
import com.climber.android.commonsdk.app.AppConstants
import com.climber.android.commonsdk.arouter.ARouterPathConstants
import com.climber.android.commonsdk.helper.openActivity
import com.climber.android.commonsdk.helper.openActivityForResult
import com.climber.android.commonsdk.util.APIDataHelper
import io.ganguo.library.mvp.http.RxSchedulers
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.RxLifecycleUtils
import io.ganguo.library.mvp.util.ToastHelper
import io.ganguo.library.mvp.util.UIUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.auth_activity_input_phone.*

/**
 * Created by Mikes at 2020-03-31 21:34
 *
 * 输入手机号
 *
 * 业务
 * 1. 修改手机号 InputPhone?otpRequestType=ModifyPhone
 * Step1. in AuthInputPhoneActivity, OTPRequestType.ModifyPhone 输入旧手机号，获取验证码 v1/send/sms type=4。
 * Step2. in AuthInputSmsCodeActivity, 输入旧手机号获取的验证码。验证手机号是否本人 v1/verify/code type=4
 *      验证旧手机号，验证通过，进入Step3，输入旧手机号获取的验证码（后台：验证旧手机号是否是已注册用户，否的话，返回异常)。
 * Step3. in AuthInputPhoneActivity, OTPRequestType.BindNewPhone  输入新手机号， 获取验证码 v1/send/sms type=5
 * Step4. in AuthInputSmsCodeActivity, 新手机号获取的验证码，绑定新手机号。 ...  v1/modify/mobile
 *
 * 2. 修改密码 InputPhone?otpRequestType=ModifyPassword
 * Step1. in AuthInputPhoneActivity, OTPRequestType.ModifyPassword 输入手机号，获取验证码 v1/send/sms type=3
 * Step2. in AuthInputSmsCodeActivity, 输入手机号获取的验证码。
 * Step3. in AuthModifyPasswordActivity,  输入新密码，确认密码. v1/modify/pwd
 *
 * 3. 忘记密码 InputPhone?otpRequestType=FindPassword
 * Step1. in AuthInputPhoneActivity, OTPRequestType.FindPassword 输入手机号，获取验证码 v1/send/sms type=2
 * Step2. in AuthInputSmsCodeActivity, 输入手机号获取的验证码，验证手机号。
 * Step3. in AuthModifyPasswordActivity,  输入新密码. v1/forget/pwd
 *
 * 4. 社交注册时绑定手机号
 * Step1. in AuthInputPhoneActivity, OTPRequestType.ModifyPhone 输入手机号，获取验证码 v1/send/sms type=1
 * Step2. in AuthInputSmsCodeActivity, 输入手机号获取的验证码。
 * Step3. 提供一个校验API
 *      1. 校验输入的手机号，已在系统内注册，则自动绑定该手机号，绑定后认为用户登录成功。 结束本流程
 *      2. 校验输入的手机号，未在系统内注册，则进入Step4 要求用户输入昵称，密码，完成社交账号注册。同时需要自动绑定该手机号。
 * Step4. in AuthSocialSignUpActivity。输入昵称，密码，完成社交账号注册。等待社交注册时绑定手机号API .... 绑定成功
 *
 */
@Route(path = ARouterPathConstants.PATH_AUTH_INPUT_PHONE)
class AuthInputPhoneActivity : BaseMVPActivity<IPresenter>() {
    private var choosedCountryCode = AppConstants.DEFAULT_COUNTRY_CODE

    companion object {
        fun openPage(activity: Activity, otpRequestType: OTPRequestType) {
            activity.openActivity(Intent(activity, AuthInputPhoneActivity::class.java)
                    .putExtra("otpRequestType", otpRequestType.name))
        }
    }

    @Autowired(name = "otpRequestType")
    @JvmField
    var otpRequestTypeName: String? = null

    private val otpRequestType: OTPRequestType by lazy {
        OTPRequestType.valueOf(intent.getStringExtra("otpRequestType"))
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun getLayoutResourceId(): Int = R.layout.auth_activity_input_phone

    override fun initView() {
        when (otpRequestType) {
            OTPRequestType.ModifyPhone -> {
                titleLabel.text = "修改手机号"
                subTitleLabel.text = "为了账号安全，请验证身份"
                confirmBtn.setText(R.string.get_sms_code)
            }
            OTPRequestType.ModifyPassword -> {
                titleLabel.text = "修改密码"
                subTitleLabel.text = "为了账号安全，请验证身份"
                confirmBtn.setText(R.string.get_sms_code)
            }
            OTPRequestType.BindNewPhone -> {
                titleLabel.text = "新手机号"
                subTitleLabel.text = "为了账号安全，请绑定手机号"
                confirmBtn.setText(R.string.get_sms_code)
            }
            OTPRequestType.FindPassword -> {
                titleLabel.text = "找回密码"
                subTitleLabel.text = "为了账号安全，请验证身份"
                confirmBtn.setText(R.string.get_sms_code)
            }
            OTPRequestType.RegisterPhone -> {
                titleLabel.text = "绑定手机号"
                subTitleLabel.text = "绑定手机号，可同步第三方账号与手机号信息"
                confirmBtn.setText(R.string.get_sms_code)
                hideNavigationIcon()
            }
        }
    }

    override fun initListener() {
        phoneNumberView.registerLeftViewClick {
            phoneNumberView.getLeftTextView().showCountryCodeSpinner(supportFragmentManager) { countryCode ->
                if (countryCode != null) choosedCountryCode = countryCode
            }
        }

        phoneNumberView.getInputView().addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                confirmBtn.isEnabled = (s?.length ?: 0) > 0
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        confirmBtn.onClick {
            doSendSmsCode()
        }
    }

    override fun initData() {
    }

    private fun doSendSmsCode() {
        val phoneNumber = phoneNumberView.getInputContent()
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastHelper.toastMessage("请输入手机号")
            return
        }

        val otpRequestInfo = otpRequestType.generateOTPRequestInfo(countryCode = choosedCountryCode, phoneNumber = phoneNumber)

        CoreService.coreServiceAPI
                .issueSendOTP(APIDataHelper.generateRequestBody(otpRequestInfo.apiParameters()))
                .compose(RxSchedulers.networkRequest<APIResponse>())
                .compose(GlobalErrorProcessor.processGlobalError(noticeErrorInfo = true))
                .doOnSubscribe {
                    UIHelper.showLoading(this)
                }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindLifecycle(this))
                .subscribe(object : ApiObserver<APIResponse>() {
                    override fun success(apiResponse: APIResponse) {
                        UIHelper.hideLoading()

                        ToastHelper.toastMessage(R.string.sms_code_has_sent_to_mobile)

                        RxCountDown.startSMSCodeCountDown(lifecycleOwner = this@AuthInputPhoneActivity,
                                countDownTickCallback = { millisUntilFinished ->
                                    confirmBtn.isEnabled = false
                                    confirmBtn.text = UIUtils.getString(R.string.get_sms_code_count_down, millisUntilFinished)
                                },
                                countDownFinishCallback = {
                                    confirmBtn.isEnabled = true
                                    confirmBtn.setText(R.string.get_sms_code)
                                })
                        if(otpRequestType == OTPRequestType.RegisterPhone){
                            openActivityForResult(Intent(this@AuthInputPhoneActivity, AuthInputSmsCodeActivity::class.java)
                                    .putExtra("otpRequestType", otpRequestType.name)
                                    .putExtra("phoneNumber", choosedCountryCode + phoneNumber)
                                    .putExtra("socialRequest", intent.getSerializableExtra("socialRequest")),
                                    0x11)
                        } else{
                            openActivityForResult(Intent(this@AuthInputPhoneActivity, AuthInputSmsCodeActivity::class.java)
                                    .putExtra("otpRequestType", otpRequestType.name)
                                    .putExtra("phoneNumber", choosedCountryCode + phoneNumber),
                                    0x11)
                        }
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()
                    }
                })
    }

    override fun onBackPressed() {
        if(otpRequestType == OTPRequestType.RegisterPhone) return
        super.onBackPressed()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            setResult(Activity.RESULT_OK, Intent().putExtra("phoneNumber", data?.getStringExtra("phoneNumber"))
                    .putExtra("smsCode", data?.getStringExtra("smsCode")))
            finish()
            overridePendingTransition(R.anim.cbase__alpha_in_activity, R.anim.cbase__alpha_out_activity)
        }
    }
}